package com.atqar.base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SynVSLock {


    //synchronized锁释放锁是jvm控制的我们无法操控,当一个线程抢锁后其他线程会等待释放会造成阻塞
    public synchronized void method1(){
        System.out.println(Thread.currentThread().getName()+"=aaa");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }



    private final Lock lock = new ReentrantLock();
    //lock.trylock 可以显式释放所资源当线程抢到锁后其他线程可以重试不必等待
    public void method2(){

        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName()+"=bbb");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }


            } finally {
                lock. unlock();
            }
        } else {
            System.out.println("抢锁失败重试");
        }
    }



    //trylock可以设置超时等待,等待时间超过这个时间就重试
    public void method3(){
        try {
            //等待超时时间设置2秒
            if(lock.tryLock(2,TimeUnit.SECONDS)){
                try {
                    System.out.println(Thread.currentThread().getName()+"=aaaa");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }finally {
                    lock.unlock();
                }
            }else {
                System.out.println("等待超过2秒后重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws InterruptedException {
        SynVSLock synVSLock = new SynVSLock();
/*
        new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method1();},"a").start();

        new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method1();},"b").start();*/


   /*     new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method2();},"a").start();

        new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method2();},"b").start();*/


        new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method3();},"a").start();

        new Thread(()-> {
            for (int i = 0; i < 10; i++) synVSLock.method3();},"b").start();

    }
/*总结synchronized是java的关键字lock是一个接口  synchronized释放锁是jvm控制的,当线程等待是会造成线程阻塞,lock是要我们unlock释放的
lock还是设置公平锁和非公平锁默认非公平锁
*/


}
